package Gui;

/*
 * CheckPanel - a panel of check boxes in one vertical column
 * 
 * Usage:
 *  String[] stringarray = {"One","Two",...};
 *  CheckPanel cp = new CheckPanel(stringarray);
 *  
 * Subclass:
 *  CheckBoxListener - increments/decrements number of boxes checked
 *  
 * To poll for checked boxes:
 *  for( int i = 0; i < cp.getNumberSelected(); i++ ){
 *    if ( cp.isSelected(i) ){
 *      // Do something
 *    }
 *  }
 *  
 * For more detailed example, see Gui.Dialogs.SellDealCardDialog
 */

import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.JCheckBox;
import javax.swing.JPanel;

public class CheckPanel extends JPanel {

	public class CheckBoxListener implements ItemListener {

		@Override
		public void itemStateChanged(ItemEvent e) {
			if (((JCheckBox) (e.getItem())).isSelected()) {
				numselected++;
			} else {
				numselected--;
			}
			changed = true;
		}

	}

	private JPanel thepanel;
	private JCheckBox[] boxes;
	private int numselected;
	private int numboxes;
	private boolean changed = false;

	public CheckPanel(String[] args) {

		thepanel = this;
		thepanel.setName("VerticalCheckBoxPanel");

		if (args != null && args.length > 0) {
			numboxes = args.length;
			boxes = new JCheckBox[numboxes];

			numselected = 0;
			changed = false;

			thepanel.setLayout(new GridLayout(numboxes, 0, 0, 5));

			CheckBoxListener cl = new CheckBoxListener();

			for (int i = 0; i < numboxes; i++) {
				boxes[i] = new JCheckBox(args[i]);
				boxes[i].addItemListener(cl);
				thepanel.add(boxes[i]);
			}
		}
	}

	public JPanel getPanel() {
		return thepanel;
	}

	public boolean isSelected(int index) {
		if (boxes != null)
			return boxes[index].isSelected();
		else
			return false;
	}

	public int getNumberSelected() {
		return numselected;
	}

	public boolean isChanged() {
		return changed;
	}

	public void setChanged(boolean aChange) {
		changed = aChange;
	}

	public JCheckBox getCheckBox(int index) {
		if (boxes != null && index >= 0 && index < boxes.length) {
			return boxes[index];
		} else {
			return null;
		}
	}

	public void uncheckAll() {
		for (int i = 0; boxes != null && i < boxes.length; i++) {
			boxes[i].setSelected(false);
		}
	}
}
